<template>
  <div class="player">
    <div class="container">
      <div class="cover">
        <!-- <el-image :src="cover" fit="cover" /> -->
      </div>
      <div class="info">
        <div class="title">{{ title }}</div>
        <div class="style">
          <span class="tags">{{ tags }}</span>
          <span class="text-lightGray"> | </span>
          <span class="time"
            >{{ formatTime(currentTime) }}<span class="split">/</span
            >{{ formatTime(duration) }}</span
          >
        </div>
      </div>

      <div class="controls-container">
        <div class="controls">
          <button @click="prevSong" class="control-btn liner-btn-opacity">
            <i class="iconfont icon-shangyiqu"></i>
          </button>
          <button @click="togglePlay" class="control-bg liner-btn-opacity cursor">
            <i class="iconfont icon-bofang ml-2" v-if="!isPlaying"></i>
            <i class="iconfont icon-zanting" v-else></i>
          </button>
          <button @click="nextSong" class="control-btn liner-btn-opacity">
            <i class="iconfont icon-xiayiqu"></i>
          </button>
        </div>
      </div>

      <div class="progress-bar" @click="setProgress" ref="progressBarRef">
        <div class="progress" :style="{ width: `${progressPercent}%` }"></div>
      </div>
      <audio
        ref="audio"
        @timeupdate="updateProgress"
        @ended="nextSong"
        @canplay="ready"
      ></audio>

      <el-button
        v-if="showClose"
        class="close"
        type="info"
        :icon="Close"
        circle
        size="small"
        @click="emits('close')"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from "vue";
import { showMessageError } from "@/utils/dialog";
import { Close } from "@element-plus/icons-vue";
import { formatTime } from "@/utils/libs";
// import { httpGet } from "@/utils/http";
import { AiImageStatusEnum } from "@/utils/ai/constants";

const audio = ref(null);
const isPlaying = ref(false);
const curIndex = ref(0);
const currentTime = ref(0);
const duration = ref(100);
const progressPercent = ref(0);
const progressBarRef = ref(null);
const songIndex = ref(0);
const title = ref("");
const tags = ref("");
const cover = ref("");
const historyIndex = ref(0);
const taskTimeout = ref(null);
// eslint-disable-next-line no-undef
const props = defineProps({
  songs: {
    type: Array,
    required: true,
    default: () => [],
  },
  showClose: {
    type: Boolean,
    default: false,
  },
  value: {
    default: 0,
  },
});
// eslint-disable-next-line no-undef
const emits = defineEmits([
  "close",
  "play",
  "nextSong",
  "prevSong",
  "update:modelValue",
]);
const ready = (params) => {
  console.log("canplay :>> ");
  isPlaying.value = true;
};

// watch(
//   () => props.songs,
//   (newVal) => {
//     console.log('props.songs :>> ', newVal);
//     songIndex.value = props.value;
//     loadSong(newVal[songIndex.value]);
//   }
// );
watch(
  () => props.value,
  (newVal) => {
    songIndex.value = newVal;
    console.log(
      "%c切换歌曲%o",
      "color: white; background-color: #f1738e; padding: 2px 5px; border-radius: 2px",
      newVal
    );
    switchIndexSong();
  }
);

const togglePlay = () => {
  if (isPlaying.value) {
    audio.value.pause();
    isPlaying.value = false;
  } else {
    play();
  }
};

const play = () => {
  console.log("play");
  if (isPlaying.value) {
    console.log("已经在播放了");
    return;
  }
  audio.value.play();
  isPlaying.value = true;
  console.log("songIndex.value :>> ", songIndex.value);
  if (audio.value.currentTime === 0) {
    emits("play");
    // 增加播放数量
    // httpGet("/api/suno/play", {
    //   song_id: props.songs[songIndex.value].song_id,
    // })
    //   .then()
    //   .catch();
  }
};
const loadSong = (song) => {
  console.log("song :>> ", song);
  if (!song) {
    showMessageError("歌曲加载失败");
    return;
  }
  if (!song.videoUrl) {
    showMessageError("歌曲地址加载失败");
    return;
  }
  if (song.status != AiImageStatusEnum.SUCCESS) {
    songIndex.value = historyIndex.value;
    showMessageError("不能播放该歌曲");
    return;
  }
  title.value = song.title;
  tags.value = song.tags;
  cover.value = song.cover_url;
  audio.value.src = song.videoUrl;
  audio.value.load();
  isPlaying.value = false;
  audio.value.onloadedmetadata = () => {
    duration.value = audio.value.duration;
  };
};
const prevSong = () => {
  emits("prevSong");
  songIndex.value =
    (songIndex.value - 1 + props.songs.length) % props.songs.length;
  playHandle();
};

const nextSong = () => {
  emits("nextSong");
  songIndex.value = (songIndex.value + 1) % props.songs.length;
  playHandle();
};
// 点击切换索引歌曲
const switchIndexSong = () => {
  playHandle();
};

const playHandle = () => {
  // 判断链接是否可以播放
  const music = new Audio();
  music.src = props.songs[songIndex.value].videoUrl;
  music.addEventListener("canplaythrough", (event) => {
    console.log(
      "%c链接允许播放",
      "color: white; background-color: #f1738e; padding: 2px 5px; border-radius: 2px"
    );
    emits("update:modelValue", songIndex.value);
    loadSong(props.songs[songIndex.value]);
    clearTimeout(taskTimeout.value);
    historyIndex.value = songIndex.value;
    taskTimeout.value = setTimeout(() => {
      console.log(
        "%c播放o",
        "color: white; background-color: #61ee98; padding: 2px 5px; border-radius: 2px",
        { cur: songIndex.value, old: historyIndex.value }
      );
      audio.value.play();
      isPlaying.value = true;
    }, 1000);
  });
  music.onerror = (error) => {
    songIndex.value = historyIndex.value;
    showMessageError("链接无法播放");
  };
};
const updateProgress = () => {
  try {
    currentTime.value = audio.value.currentTime;
    progressPercent.value = (currentTime.value / duration.value) * 100;
  } catch (e) {
    console.error(e.message);
  }
};

const setProgress = (event) => {
  const totalWidth = progressBarRef.value.offsetWidth;
  const clickX = event.offsetX;
  const audioDuration = audio.value.duration;
  audio.value.currentTime = (clickX / totalWidth) * audioDuration;
};

// eslint-disable-next-line no-undef
defineExpose({
  play,
});

onMounted(() => {
  songIndex.value = props.value;
  historyIndex.value = props.value;
  loadSong(props.songs[songIndex.value]);
});
</script>

<style lang="stylus" scoped>

.player {
  display flex
  justify-content center
  width 100%

  .container {
    display flex
    // background-color: #363030;
    background: linear-gradient(120deg, #222935 100%, #242C39 100%, #283140 100%);
    border-radius:10px;
    padding: 10px;
    width: 100%
    text-align: center;
    position relative
    overflow hidden


    .cover {
      .el-image {
        // border-radius: 50%;
        width 40px
      }
    }

    .info {
      padding 0 10px
      min-width 37%
      display flex
      justify-content center
      align-items flex-start
      flex-flow column
      line-height 2

      .title {
        // font-weight 700
        font-size 13px
        color #CCCCFF
      }

      .style {
        font-size 10px
        display flex
        color #e1e1e1
        .tags {
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden;    /* 隐藏溢出的文本 */
          text-overflow: ellipsis; /* 使用省略号表示溢出的文本 */
          max-width 200px
        }
        .text-lightGray {
          color: rgb(114 110 108);
          padding 0 3px
        }
        .time {
          font-family 'Input Sans'
          // font-weight 700
          .split {
            font-size 10px
            position relative
            top 0
            margin 0 1px 0 3px
          }
        }
      }
    }

    .controls-container {
      display flex
      flex-flow column
      justify-content center

      .controls {
        width 160px;
        margin:13px auto 10px auto;
        display: flex;
        justify-content: space-around;
        .control-bg{
          width 30px;
          height: 30px;
          line-height: 30px
          background: linear-gradient(120deg, #5b97ff 30%, #62e3ff 60%, #64f3fe 100%);
          border-radius:50px
          color: #000
          border:none;
        } 
        .control-btn {
          background: none;
          border:none;
          color: #7d839c;
          cursor: pointer;
          padding 6px
          .iconfont {
            font-size 20px
          }
        }

      }
    }

    .progress-bar {
      position absolute
      width 100%
      left 0
      top 0
      height:5px;
      background-color: #77718E;
      cursor: pointer;

      .progress {
        height: 100%;
        background-color: #33CCFF;
        border-radius: 5px;
        width: 0;
      }

    }

    .close {
      position absolute
      right 10px
      top 15px
    }
  }
}
</style>
